package com.example.enterprise.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

public class FileUploadUtils {


    public static String upload(MultipartFile photo, HttpSession session, String domain, String uploadPath) {
        String realPath = uploadPath;
        try {
            if (!photo.isEmpty()) {
                //String realPath = session.getServletContext().getRealPath("D:\\workspace\\upload\\");

                String originalFilename = photo.getOriginalFilename();

                if (originalFilename.endsWith(".png") || originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg") || originalFilename.endsWith(".mp4")) {
                    String replace = UUID.randomUUID().toString().replace("-", "");


                    String filename = replace + originalFilename;
                    File file = new File(uploadPath, filename);
                    photo.transferTo(file);
                    realPath += filename;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return realPath;
    }

    public static void showImg(String path, HttpServletResponse response) {
        if (path != null && !path.equals("")) {

            try {
                FileInputStream fis = new FileInputStream(path);
                ServletOutputStream os = response.getOutputStream();

                byte[] b = new byte[1024 * 8];
                while (fis.read(b) != -1) {
                    os.write(b);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}